/*********************************************************
          File Name:main.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Wed 09 Sep 2015 11:00:07 AM CST
**********************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <sys/uio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "../../inf/sock.h"
#include "sendfd.h"

void child(void)
{
        int unix_fd = 0;
        int fd = 0;

        do{
                unix_fd = unix_connect("./unix_domain");
        } while(unix_fd == -1);

        unlink("./unix_domain");

        fd = rcvsockfd(unix_fd);
        if(fd == -1)
                perror("child");
        else
                printf("receive from parent\n");

        write(fd, "child\n", 6);
        close(fd);
        close(unix_fd);
}

int main(void)
{
        int sockfd = 0;
        int connfd = 0;
        pid_t pid = 0;
        int fd = 0;

        sockfd = unix_socket("./unix_domain", 5);


        if(sockfd == -1)
                exit(1);

        pid = fork();
        if(pid == 0)
                child();
        
        if(pid > 0)
        {
                connfd = accept(sockfd, NULL, NULL);


                fd = open("test", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);

                if(sndsockfd(connfd, fd) == -1)
                        perror("parent");
                else
                        printf("send to child\n");
        }
        wait(NULL);

        close(fd);

        return 0;
}
